package com.taoye.thread;

import java.util.ArrayList;
import java.util.List;

/**
 * @author : Mr.Tao
 * @version : 1.0
 * @date : 2022/4/3 16:43
 **/
public class Demo38 {
    public static void main(String[] args) throws InterruptedException {
        List<Integer> list = new ArrayList<>();
        Thread t1 = new Demo38ThreadB(list);
        t1.setName("B");
        t1.start();
        Thread t = new Demo38ThreadA(list);
        t.setName("A");
        t.start();
    }
}

class Demo38ThreadA extends Thread {
    private List<Integer> list;

    public Demo38ThreadA(List<Integer> list) {
        this.list = list;
    }

    @Override
    public void run() {
        synchronized (list) {
            try {
                for (int i = 0; i < 10; i++) {
                    list.add(i);
                    System.out.println("添加了数字：" + i);
                    if (list.size() == 5) {
                        System.out.println("A线程已经添加了5个元素，通知B线程结束");
                        list.notify();
                    }
                    Thread.sleep(1000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}

class Demo38ThreadB extends Thread {
    private volatile List<Integer> list;

    public Demo38ThreadB(List<Integer> list) {
        this.list = list;
    }

    @Override
    public void run() {
        try {
            synchronized (list) {
                System.out.println("我是线程B，我等A线程通知我结束哦~");
                list.wait();
                System.out.println("我是线程B，我现在结束运行了。");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
